package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.business.BusinessDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.dto.business.BusinessesPoolDTO;
import com.qk.dto.business.UpdateBusinessInfoDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author: byLengs
 * @Date: 2025/10/15 10:58
 * @Description:
 */
@Service
@SuppressWarnings("all")
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;

    @Override
    public PageResult<Business> businessesPoolList(BusinessesPoolDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<Business> page = this.businessMapper.selectBusinessesPoolList(dto);
        return PageResult.<Business>builder()
                .total(page.getTotal())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void backBusinessPool(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.RECOVERY);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void toCustomer(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.CONVERT_TO_CUSTOMER);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);
        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setId(null);
        customer.setBusinessId(id);
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        this.customerMapper.insert(customer);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBusinessInfoById(UpdateBusinessInfoDTO dto) {
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setUpdateTime(LocalDateTime.now());
        if (dto.getStatus() == BusinessStatusConstants.WAIT_FOLLOW_UP) {
            business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(business);
        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        // 手动处理 keyItems 类型转换
        if (dto.getKeyItems() != null && !dto.getKeyItems().isEmpty()) {
            businessTrackRecord.setKeyItems(String.join(",", dto.getKeyItems()));
        }
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecord.setId(null);
        businessTrackRecord.setBusinessId(business.getId());
        businessTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.businessTrackRecordMapper.insert(businessTrackRecord);
    }

    @Override
    public BusinessVO getBusinessInfoById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        String name = this.userMapper.selectById(business.getUserId()).getName();
        List<BusinessTrackRecord> businessTrackRecords = businessTrackRecordMapper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                .in(BusinessTrackRecord::getBusinessId, id));
        BusinessVO businessVO = BeanUtil.copyProperties(business, BusinessVO.class);
        List<BusinessVO.TrackRecords> list = businessTrackRecords.stream().map(item -> {
            BusinessVO.TrackRecords recordVO = BeanUtil.copyProperties(item, BusinessVO.TrackRecords.class);
            // 手动处理 keyItems 类型转换
            if (item.getKeyItems() != null && !item.getKeyItems().isEmpty()) {
                List<String> keyItemsList = Arrays.asList(item.getKeyItems().split(","));
                recordVO.setKeyItems(keyItemsList);
            }
            recordVO.setAssignName(name);
            return recordVO;
        }).toList();
        businessVO.setTrackRecords(list);
        return businessVO;
    }

    @Override
    public PageResult<BusinessDO> businessList(BusinessListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<BusinessDO> page = businessMapper.selectByPage(dto);
        return PageResult.<BusinessDO>builder()
                .total(page.getTotal())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void addBusiness(BusinessDTO dto) {
        if (ObjectUtil.isNull(dto.getPhone()) || Objects.isNull(dto.getPhone())) {
            throw new RuntimeException("参数错误");
        }
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        businessMapper.insert(business);
    }
}
